package com.example.rwq_test.threadFrequencyAdapter;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 动态调整定时调度线程频率
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/1/10
 */
@Slf4j
public class DynamicThreadFrequencyAdapter {

    public static final ScheduledExecutorService SCHEDULE_POOL = Executors.newScheduledThreadPool(20);
    public static final Map<String, ScheduledFuture<?>> SCHEDULED_FUTURE_MAP = new HashMap<>();

    public static void addScheduledFutureMap(String key, ScheduledFuture<?> future){
        SCHEDULED_FUTURE_MAP.put(key, future);
    }

    public static ScheduledFuture<?> getScheduledFuture(String key) {
        return SCHEDULED_FUTURE_MAP.get(key);
    }

    /**
     * 修改频率
     * @param key
     * @param frequency
     */
    public static void resetFrequency(String key, Integer frequency) {
        try {
            ScheduledFuture<?> scheduledFuture = getScheduledFuture(key);
            if (scheduledFuture != null) {
                scheduledFuture.cancel(true);
            }
            SCHEDULED_FUTURE_MAP.put(key, SCHEDULE_POOL.scheduleAtFixedRate(new ScheduleWorker(), frequency, frequency, TimeUnit.MILLISECONDS));
        } catch (Exception e) {
        }
    }

    public static class ScheduleWorker implements Runnable {

        @Override
        public void run() {
            log.info("start work...");
        }
    }

    public static void main(String[] args) {
        ScheduleWorker scheduleWorker = new ScheduleWorker();
        addScheduledFutureMap("ScheduleWorker", SCHEDULE_POOL.scheduleAtFixedRate(scheduleWorker, 1000,2000, TimeUnit.MILLISECONDS));
        try {
            TimeUnit.MILLISECONDS.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        resetFrequency("ScheduleWorker", 500);
        try {
            TimeUnit.MILLISECONDS.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
